package org.luxor.commons.schedule.job.impl;

import org.luxor.commons.core.utils.DateUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 定时器使用样例
 */
@Service
public class ScheduleTaskServiceImpl {

    @Async
    @Scheduled(cron = "* * * * * ?") // 每秒执行一次
    public void cronRateSeconds() {
        Date date = new Date();
        System.out.println("【RateSeconds】ThreadName:{" + Thread.currentThread().getName() + "}  runTime:{" + DateUtils.format(date, DateUtils.DATE_TIME_PATTERN) + "}");
    }

    @Scheduled(cron = "0 */5 * * * ?") // 每5分钟执行一次
    public void cronRate5Minutes() {
        Date date = new Date();
        System.out.println("【Rate2Seconds】ThreadName:{" + Thread.currentThread().getName() + "}  runTime:{" + DateUtils.format(date, DateUtils.DATE_TIME_PATTERN) + "}");
    }

    @Scheduled(cron = "0 0 23 * * ?") // 每天晚上23点整执行一次
    public void CronRateDay() {
        Date date = new Date();
        System.out.println("【RateDay】ThreadName:{" + Thread.currentThread().getName() + "}  runTime:{" + DateUtils.format(date, DateUtils.DATE_TIME_PATTERN) + "}");
    }

    @Scheduled(fixedDelay = 5 * 1000) // 上一次执行完毕之后5秒再执行(循环间隔5秒)。
    public void fixedDelay() {
        Date date = new Date();
        System.out.println("【fixedDelay】ThreadName:{" + Thread.currentThread().getName() + "}  runTime:{" + DateUtils.format(date, DateUtils.DATE_TIME_PATTERN) + "}");
    }

    // fixedDelayString与fixedDelay的作用是一样的，只是参数类型为String,且支持表达式传参
    @Scheduled(fixedDelayString = "${time:5000}") // 上一次执行完毕之后5秒再执行(循环间隔5秒)。
    public void fixedDelayString() {
        Date date = new Date();
        System.out.println("【fixedDelayString】ThreadName:{" + Thread.currentThread().getName() + "}  runTime:{" + DateUtils.format(date, DateUtils.DATE_TIME_PATTERN) + "}");
    }

    @Scheduled(fixedRate = 5000) // 上一次开始执行时间点之后多长时间再执行(循环间隔5秒)
    public void fixedRate() {
        Date date = new Date();
        System.out.println("【fixedRate】ThreadName:{" + Thread.currentThread().getName() + "}  runTime:{" + DateUtils.format(date, DateUtils.DATE_TIME_PATTERN) + "}");
    }

    @Scheduled(initialDelay = 1000, fixedRate = 5000) //容器启动后延迟1秒后执行定时器，之后按fixedRate的规则每5秒执行一次
    public void initialDelayFixedRate() {
        Date date = new Date();
        System.out.println("【initialDelay】ThreadName:{" + Thread.currentThread().getName() + "}  runTime:{" + DateUtils.format(date, DateUtils.DATE_TIME_PATTERN) + "}");
    }

}
